<!--echarts 通用组件-->
<template>
  <div
      v-if="!state.isDispose"
      :id="echartsComponents"
      style="width: 100%;height: 100%"
  />
</template>

<script setup>
import * as echarts from 'echarts';


import {computed, onMounted, onUnmounted, reactive, watchEffect} from "vue";


const props = defineProps({
  chartDataOptions: {
    type: Object, // 此处可以为Array或者Object或者
  },
  isMap: {
    type: Boolean,
    default: false
  },
  geoJson:{
    type: JSON,
    default: null
  }
})

// 计算属性
const echartsComponents = computed(() => {
  const timestamp = new Date().getTime();
  return `echarts${timestamp}${Math.random() * 100000}`;
});

let myEcharts = null

const state = reactive({
  isDispose: false,
  screenWidth: 0, // 频幕宽度
})


onMounted(() => {
  state.screenWidth = document.body.clientWidth;
  initEcharts();
  window.addEventListener('resize', resizeMyChart);

})

onUnmounted(() => {
  window.removeEventListener('resize', resizeMyChart);
})

const initEcharts = () => {
  state.isDispose = false;
  const $echartsDOM = document.getElementById(echartsComponents.value);
  myEcharts = echarts.init($echartsDOM);
  if(props.isMap){
    echarts.registerMap('china', props.geoJson);
  }
  refreshEcharts()
}

// 图表刷新
const refreshEcharts = () => {
  if(!props.chartDataOptions) return
  // 渲染数据
  const option = props.chartDataOptions;
  myEcharts.clear();
  myEcharts.setOption(option);
}

watchEffect(() =>{
  if(props.chartDataOptions && myEcharts){
    refreshEcharts();
  }
})


const resizeMyChart = () => {
  setTimeout(() => {
    myEcharts.resize();
    refreshEcharts()
  }, 200)
}

defineExpose({
  getEChartsInstance () {
    return myEcharts;
  },
  refreshEcharts: () => {
    refreshEcharts()
  },
})

</script>
